# !/usr/bin/env python
# coding:utf-8
"""
    Author = 上善若水(QQ:564667570)
    Affiliation = Institute of Subtropical Agriculture, Chinese Academy of Sciences
    Time = '2018-3-12, 20:38'
"""

# 协程 asynchronous programming

# from types import coroutine
# import asyncio
#
# async def ping_server():
#     pass
#
# @asyncio.coroutine
# def load_file(path):
#     file_content = yield from load_file()

# import asyncio
# async def speak_async():
#     print('OMG asynchronicity!')
# loop = asyncio.get_event_loop()
# loop.run_until_complete(speak_async())
# loop.close()

# import signal
# import sys
# import asyncio
# import aiohttp
# import json
#
# loop = asyncio.get_event_loop()
# client = aiohttp.ClientSession(loop=loop)
#
# async def get_json(client, url):
#     async with client.get(url) as response:
#         assert response.status == 200
#         return await response.read()
#
# async def get_reddit_top(subreddit, client):
#     data1 = await get_json(client,'https://www.reddit.com/r/' + subreddit + '/top.json?sort=top&t=day&limit=5')
#
#     j = json.loads(data1.decode('utf-8'))
#     for i in j['data']['children']:
#         score = i['data']['score']
#         title = i['data']['title']
#         link = i['data']['url']
#         print(str(score) + ':' + title + '(' + link + ')')
#
#     print('DONE:', subreddit + '\n')
#
# def signal_handler(signal, frame):
#     loop.stop()
#     client.close()
#     sys.exit(0)
#
# signal.signal(signal.SIGINT, signal_handler)
#
# asyncio.ensure_future(get_reddit_top('python', client))
# asyncio.ensure_future(get_reddit_top('programming', client))
# asyncio.ensure_future(get_reddit_top('compsci', client))
# loop.run_forever()

# def eager_range(up_to):
#     """Create a list of integers, from 0 to up_to, exclusive."""
#     sequence = []
#     index = 0
#     while index < up_to:
#         sequence.append(index)
#         index += 1
#     return sequence
#
# def lazy_range(up_to):
#     """Generator to return the sequence of integers from 0 to up_to, exclusive."""
#     index = 0
#     while index < up_to:
#         yield index
#         index += 1
#
# eager = lazy_range(20)
# print(eager)

def jumping_range(up_to):
    """Generator for the sequence of integers from 0 to up_to, exclusive.

    Sending a value into the generator will shift the sequence by that amount.
    """
    index = 0
    while index < up_to:
        jump = yield index
        if jump is None:
            jump = 1
        index += jump


if __name__ == '__main__':
    iterator = jumping_range(5)
    print(next(iterator))  # 0
    print(iterator.send(2))  # 2
    print(next(iterator))  # 3
    print(iterator.send(-1))  # 2
    for x in iterator:
        print(x)  # 3, 4